<template>
  <div class="input-counter">
    <button class="btn btn-default btn-sm input-counter-left" @click="sub" type="button" :disabled="counter <= validMin">-</button>
    <input type="text" :value="counter" @input="onChange" size="8" :disabled="field.disabled">
    <button class="btn btn-default btn-sm input-counter-right" @click="plus" type="button" :disabled="counter >= validMax">+</button>
  </div>
</template>

<script>
  import _ from 'lodash'

  export default {
    props: {
      field: {
        max: {
          type: Number
        },
        min: {
          type: Number
        },
        disabled: Boolean
      },
      value: {
        default: 1
      }
    },
    computed: {
      validMin () {
        let min = +this.field.min
        if (_.isNaN(min) || min <= 0) {
          min = 0
        }
        return min
      },
      validMax () {
        let max = +this.field.max
        if (_.isNaN(max) || max <= 0) {
          max = 999
        }
        return max
      },
      counter: {
        get () {
          let v = Math.ceil(+this.value)
          if (_.isNaN(v)) {
            return 0
          }
          return v
        },
        set (v) {
          v = +v
          if (_.isNaN(v) || v < 0) {
            v = 0
          }
          v = Math.ceil(v)
          this.$emit('input', v)
        }
      }
    },
    methods: {
      onChange (e) {
        let v = +e.target.value
        if (_.isNaN(v) || v < this.validMin || v > this.validMax) {
          v = this.counter
        } else {
          v = Math.ceil(v)
        }
        if (e.target.value !== v + '') {
          e.target.value = this.counter
        }
        this.counter = v
      },
      plus () {
        this.counter = this.counter + 1
      },
      sub () {
        if (this.counter > 0) {
          this.counter = this.counter - 1
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  $height: 30px;
  $width: 30px;

  .input-counter {
    position: relative;
    display: inline-block;

    button {
      border-radius: 0 !important;
      outline: none !important;
    }

    input {
      line-height: $height;
      height: $height;
      width: $width * 2 + 40px;
      padding: 0 $width;
      text-align: center;
      border-top: solid 1px #ccc;
      border-bottom: solid 1px #ccc;
      border-left: none;
      border-right: none;
      outline: none !important;
    }

    button {
      position: absolute;
      top: 0;
      height: $height;
      width: $width;
      line-height: $height;
      padding: 0;
      vertical-align: middle;
    }
    .input-counter-left {
      left: 0;
    }
    .input-counter-right {
      right: 0;
    }
  }
</style>
